/**
 * Copyright (C), 2015-2019, 静修教育咨询有限公司
 * FileName: PayController
 * Author:  SAGIRI
 * Date:     2019/7/13 0013 14:45
 * Description: 支付控制器
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.ruimei.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayUtil;
import com.ruimei.entitys.BillingRecords;
import com.ruimei.service.IPayService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 〈概要〉<br>
 * 〈支付控制器〉
 *
 * @author SAGIRI
 * @create 2019/7/13 0013
 * @since 1.0.0
 */
@RestController
public class PayController {
    private static final Logger logger = LoggerFactory.getLogger(PayController.class);

    @Resource
    private IPayService payService;

    @Autowired
    private RestTemplate restTemplate;
    /**
     * @Description:微信小程序统一下单
     * @param request
     * @return
     * JsonResult<String>
     * @exception:
     * @author: hemiao
     * @time:2018年8月1日 下午2:09:47
     */
    @RequestMapping(value="/wx/pay",method = RequestMethod.GET)
    public JSONObject unifiedOrder(HttpServletRequest request) throws Exception{
        JSONObject object = new JSONObject();
        //订单编号
        String noticeId = request.getParameter("noticeId");
        String msg ;
        if(StringUtils.isBlank(noticeId)) {
            msg = "必要信息不能为空";
            logger.info(msg);
            object.put("status",false);
            object.put("msg",msg);
            return object;
        }
        // 根据订单查询 订单信息
        BillingRecords billingRecords = payService.queryPaymentInformation(noticeId);
        if(billingRecords==null) {
            msg = "订单不存在";
            logger.info("根据orderNo="+noticeId+","+msg);
            object.put("status",false);
            object.put("msg",msg);
            return object;
        }

        //结算金额
        BigDecimal payPrice = billingRecords.getMoney();
        // 订单支付金额
        if(!(payPrice.compareTo(new BigDecimal(0))==1)) {
            object.put("msg","订单金额必须大于0");
            object.put("status",false);
            return object;
        }
        BigDecimal total_fee = payPrice.multiply(new BigDecimal(100)).setScale(0,BigDecimal.ROUND_HALF_UP);

        //商品名称信息
        String body = billingRecords.getType();
        String attach = "成都静修教育咨询有限公司";
        //终端IP
        String spbill_create_ip = request.getRemoteAddr();
        //支付回调 通知地址
        SortedMap<String, String> packageParams = new TreeMap<>();
        //根据appid获取自己的商户
        packageParams.put("appid","wx56ffb55836fd61a8");
        packageParams.put("mch_id","1501724851");
        packageParams.put("nonce_str",WXPayUtil.generateNonceStr());
        String sign = WXPayUtil.generateSignature(packageParams, "wx56ffb55836fd61a8");
        packageParams.put("sign",sign);
        packageParams.put("body","测试支付");
        packageParams.put("out_trade_no",UUID.randomUUID().toString().replace("-",""));
        packageParams.put("total_fee",total_fee.toString());
        packageParams.put("spbill_create_ip",request.getRemoteAddr());
        packageParams.put("notify_url","http://d4wmqk.natappfree.cc/payCallBack");
        packageParams.put("trade_type","JSAPI");
        String xml= WXPayUtil.mapToXml(packageParams);
       String resultObj =  restTemplate.postForObject("https://api.mch.weixin.qq.com/pay/unifiedorder",xml,String.class);
       Map<String,String> map  = WXPayUtil.xmlToMap(resultObj);
       return JSON.parseObject(JSONObject.toJSONString(map));
    }







    /**
     * @Description:微信小程序支付回调地址
     * @param request
     * @throws IOException
     * void
     * @exception:
     * @author: hemiao
     * @time:2018年8月1日 下午1:56:01
     */
    @RequestMapping(path="/payCallBack")
    @ResponseBody
    public synchronized String payCallBack(HttpServletRequest request) throws Exception{
        request.setCharacterEncoding("utf-8");
        String result = "failure";
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line ;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null){
            sb.append(line);
        }
        logger.info("微信小程序支付回调Xml-->:"+sb.toString());
        if(StringUtils.isBlank(sb)) {
            return result;
        }
        Map<String, String> map = WXPayUtil.xmlToMap(sb.toString());
        // 订单编号
        String orderNo = map.get("out_trade_no");
        // 单位为分，要转成元
        String money = map.get("total_fee");
        BigDecimal totalFee = new BigDecimal(money).divide(new BigDecimal("100"));

        // 根据订单单号，查询本地的订单信息
        logger.info("小程序支付回调，订单编号："+orderNo);

        // 获取该订单的状态，看是否已经付款
        if(true){
            return "success";
        }
        return result;
    }

}
